package com.kc.statistics;

import com.alibaba.fastjson.JSON;
import com.kc.statistics.bean.Statistics;
import com.kc.statistics.bean.TrackEvent;
import com.kc.statistics.dao.StatisticsDao;
import com.kc.statistics.httpmodel.MobileVO;
import com.kc.statistics.httpmodel.StatisticsParms;
import com.kc.statistics.ip.IPSeeker;
import com.kc.statistics.utils.*;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import com.kc.statistics.httpmodel.MobileVO;

@Controller
public class StatisticsController {
	private static final Logger log = LoggerFactory.getLogger(StatisticsController.class);

	@Autowired
	private IPSeeker iPSeeker;

	@Autowired
	private StatisticsDao statisticsDao;

	@RequestMapping(value = { "/track/hm.gif" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	// @ResponseBody
	public void track(HttpServletRequest request, HttpServletResponse response, String data) {

		try {
			// ��Խ����
			request.setCharacterEncoding("UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
			response.setHeader("Access-Control-Max-Age", "3600");
			response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
			response.setContentType("image/jpeg");

			if (StringUtils.isNotBlank(data)) {
				/**
				 * % ��URL���������ַ�����Ҫ����ת��
				 */

				data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
				data = URLDecoder.decode(data, "UTF-8");
				data = URLDecoder.decode(data, "UTF-8");

				// base64����
				byte[] encodeBase64 = Base64.decodeBase64(data.getBytes("utf-8"));
				String strdata = new String(encodeBase64, "UTF-8");

				List<MobileVO> MobileVOs = JSON.parseArray(strdata, MobileVO.class);
				// ����ȫ����¼
				for (MobileVO mobileVO : MobileVOs) {
					statisticsDao.saveMobileVo(mobileVO);
				}

			}

			// ����gif
			ServletOutputStream os = response.getOutputStream();
			BufferedImage im = ImageUtils.generateImageIo();
			ImageIO.write(im, "gif", os);
			os.close();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// return "";
	}

	@RequestMapping(value = { "/hm.gif" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public void hm(HttpServletRequest request, HttpServletResponse response, StatisticsParms p, TrackEvent trackEvent) {
		try {
			// ��Խ����
			request.setCharacterEncoding("UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
			response.setHeader("Access-Control-Max-Age", "3600");
			response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
			response.setContentType("image/jpeg");

			// ������Ϊ�վ����
			if (null != p || null != trackEvent) {
				String ipAddr = IpUtils.getIpAddr(request);

				// �����������봫�������
				p.setTt(DecodeUtils.decode(p.getTt()));
				p.setSu(DecodeUtils.decode(DecodeUtils.decode(p.getSu())));
				p.setNu(DecodeUtils.decode(DecodeUtils.decode(p.getNu())));

				Statistics st = new Statistics();
				BeanUtils.copyProperties(st, p);
				st.setIp(ipAddr);

				st.setAt(DateUtils.getDateMs());// ���÷�����ʱ��

				/**
				 * ʶ���û�IP, �������Ӫ��
				 */
				if (StringUtils.isNotBlank(st.getIp())) {

					// �����Ƿ���IP
					String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
					Pattern pp = Pattern.compile(regex);
					Matcher m = pp.matcher(st.getIp());
					if (m.find()) {
						String area = "";
						String country = "";
						try {
							area = iPSeeker.getCountry(st.getIp());// ����
							country = iPSeeker.getArea(st.getIp());// ������Ӫ��
							area = AreaUtils.findArea(area);// ��ȡʡ��
							if (StringUtils.isNotBlank(area)) {
								st.setAr(area);
							}
							if (StringUtils.isNotBlank(country)) {
								st.setNetopt(country);
							}
						} catch (Exception e) {
							// log.error(e.getMessage(),e);
						}
					}

				}

				// Э��ͷ����
				if (!StringUtils.isBlank(st.getUa())) {
					UserAgent userAgent = UserAgent.parseUserAgentString(st.getUa());
					Browser browser = userAgent.getBrowser();
					OperatingSystem os = userAgent.getOperatingSystem();
					st.setBrowser(browser.getName());
					st.setOs(os.getName());
					st.setDevicetype(os.getDeviceType().getName());
				}

				/**
				 * ������¼�����
				 */
				if ((StringUtils.isNotBlank(trackEvent.getTag())) && (trackEvent.getTag().equals("_trackEvent"))) {
					String ct = trackEvent.getCt();
					ct = DecodeUtils.decode(ct);
					String at = trackEvent.getAt();
					at = DecodeUtils.decode(at);
					String kl = trackEvent.getKl();
					kl = DecodeUtils.decode(kl);
					String vl = trackEvent.getVl();
					vl = DecodeUtils.decode(vl);
					trackEvent.setCt(ct);
					trackEvent.setAt(at);
					trackEvent.setKl(kl);
					trackEvent.setVl(vl);
					// ����
					statisticsDao.savetrackEvent(trackEvent, st);
					// log.info(" ��������� �¼����� ������" + trackEvent.toString());
				} else {
					// log.info("���������PV �Ĳ�����" + st.toString());
					statisticsDao.saveStatistics(st);
				}
			}

			ServletOutputStream os = response.getOutputStream();
			BufferedImage im = ImageUtils.generateImageIo();
			ImageIO.write(im, "gif", os);
			os.close();
		} catch (Exception e) {
			log.error("ͳ�����ݽӿڳ��� ", e.getMessage());
		}
	}
}